package com.java.com.syun.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class AIOClient {
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        Future<Void> future = client.connect(new InetSocketAddress("127.0.0.1", 9002));
        future.get();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        client.read(buffer, null, new CompletionHandler<Integer, Void>() {
            //成功时调用
            @Override
            public void completed(Integer result, Void attachment) {
                System.out.println("接收服务端消息：" + new String(buffer.array()));
            }
            //失败时调用
            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("客户端接收消息失败");
            }
        });

        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
        writeBuffer.put("客户端 TO 服务端 ：say hi".getBytes());
        writeBuffer.flip();

        Future<Integer> write = client.write(writeBuffer);
        Integer r = write.get();
        if(r>0){
            System.out.println("客户端消息发送成功");
        }
       //休眠线程
        TimeUnit.SECONDS.sleep(1000L);
    }
}
